﻿using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading;

namespace ManhattanProcedure.Model
{
    public class CoffeeIOMsgR
    {
        private static CoffeeIOMsgR instance;
        private CoffeeIOMsgR() { }

        public static CoffeeIOMsgR Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new CoffeeIOMsgR();
                }
                return instance;
            }
        }
        #region IO通讯
        public bool AllBol = true;
        public bool RobotBol = true;
        public delegate void IOdelegate(string btnName, string tag);
        public IOdelegate iodelegate;
        /// <summary>
        ///  IO的通讯返回数据
        /// </summary>
        private List<byte> buffer = new List<byte>();
        public static bool IsMsgError = true;
        string nostrs = "";
        public Thread All_thr;
        public void QK()
        {
            try
            {
                Thread.Sleep(100);
                CoffeeIOSerialPortR.Instance.SerialSend(CoffeeIOModel.Instance.KSZZ_Robot_Right_End);
                Thread.Sleep(100);
                CoffeeIOSerialPortR.Instance.SerialSend(CoffeeIOModel.Instance.BKF_Robot_Right_End);
                Thread.Sleep(100);
                CoffeeIOSerialPortR.Instance.SerialSend(CoffeeIOModel.Instance.LHKF_Robot_Right_End);
                Thread.Sleep(100);
                CoffeeIOSerialPortR.Instance.SerialSend(CoffeeIOModel.Instance.CBWC_Robot_Right_End);
                Thread.Sleep(100);
                CoffeeIOSerialPortR.Instance.SerialSend(CoffeeIOModel.Instance.QDB_Robot_Right_End);
                Thread.Sleep(100);
                CoffeeIOSerialPortR.Instance.SerialSend(CoffeeIOModel.Instance.JNWC_Robot_Right_End);
                Thread.Sleep(100);
                CoffeeIOSerialPortR.Instance.SerialSend(CoffeeIOModel.Instance.QQX_Robot_Right_End);
                Thread.Sleep(100);
                CoffeeIOSerialPortR.Instance.SerialSend(CoffeeIOModel.Instance.QXWC_Robot_Right_End);
                Thread.Sleep(100);
                CoffeeIOSerialPortR.Instance.SerialSend(CoffeeIOModel.Instance.QJN_Robot_Right_End);
                Thread.Sleep(100);

            }
            catch (Exception)
            {
                return;
            }
        }
        public void IOSerial_Thr()
        {
            try
            {
                var ddd = SerialPort.GetPortNames().ToList();
                if (!SerialPort.GetPortNames().ToList().Any(a => a.ToLower().Contains(IPorPortInfo.Instance.IOCoffeePortNameR)))
                {
                    Thread.Sleep(1000);
                    IOSerial_Thr();
                }
                CoffeeIOSerialPortR.Instance.IceMachineConnect(IPorPortInfo.Instance.IOCoffeePortNameR, 38400, "", 8, 1);//其他串口通讯
                CoffeeIOSerialPortR.Instance.serialPort.DataReceived += SerialPort_DataReceived;
                Instance.QK();
            }
            catch (Exception)
            {
                CoffeeIOSerialPortR.Instance.serialPort.DataReceived -= SerialPort_DataReceived;
                Thread.Sleep(100);
                IOSerial_Thr();
            }
        }
        /// <summary>
        /// PING 通 IP
        /// </summary>
        /// <param name="IP"></param>
        /// <returns></returns>
        public bool PingIP(string IP)
        {
            try
            {
                if (IP.Split('.').Count() < 4) return false;
                Ping pingSender = new Ping();
                PingReply reply = pingSender.Send(IP, 120);//第一个参数为ip地址，第二个参数为ping的时间
                if (reply.Status == IPStatus.Success)
                {
                    return true;
                }
                else
                {
                    //ping不通
                    return false;
                }
            }
            catch (Exception)
            {
                return false;
            }
        }

        public void AllMessages()
        {
            try
            {
                while (true)
                {
                    try
                    {
                        if (Instance.AllBol)
                            CoffeeIOSerialPortR.Instance.SerialSend(CoffeeIOModel.Instance.AllMessage);
                        Thread.Sleep(100);
                    }
                    catch (Exception)
                    {
                        Thread.Sleep(100);
                    }

                }
            }
            catch (Exception)
            {
                CoffeeIOSerialPortR.Instance.serialPort.DataReceived -= SerialPort_DataReceived;
                Thread.Sleep(100);
                IOSerial_Thr();
            }
        }
        private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                var dd = CoffeeIOSerialPortR.Instance.serialPort.BytesToRead;
                byte[] result = new byte[dd];
                CoffeeIOSerialPortR.Instance.serialPort.Read(result, 0, dd);
                string str = "";// $"{DateTime.Now}：\n";
                                //判断读写模式
                    str += $"{Encoding.ASCII.GetString(result)}";
                for (int i = 0; i < result.Length; i++)
                {
                    str += $"{result[i].ToString("X2")} ";
                }
                MsgShow(str);
                Thread.Sleep(1);
            }
            catch (Exception)
            {
                return;
            }
        }
        string strlist = "";
        public void MsgShow(string str)
        {
            try
            {
                // Console.WriteLine(str);
                nostrs = "";
                var nostr = str.Split(' ');
                nostrs += nostr[0].Substring(nostr[0].Length - 2, 2) + " ";
                for (int i = 1; i < nostr.Count() - 1; i++)
                {
                    nostrs += nostr[i] + " ";
                }
                if (nostrs.Substring(0, 5) == "01 05")
                {
                    Console.WriteLine(str);
                }
                else if (nostrs.Substring(0, 5) == "02 04")
                {
                    strlist = nostrs;
                }
                else if (nostrs.Substring(0, 5) == "05 02")
                {
                    Console.WriteLine(nostrs);
                    var robstr = nostrs.Split(' ');
                    RobotBol = robstr[3] == "01" ? true : false;
                    Console.WriteLine(robstr[3] == "01" ? true : false);
                }
                else
                {
                    if (strlist != "")
                        strlist += nostrs;
                }
                //if (strlist.Split(' ').Count() >= 105)
                //{
                //    CoffeeIOModelBol2(strlist);
                //    strlist = "";
                //}
            }
            catch (Exception)
            {
                return;
            }
        }

        #endregion
    }
}
